import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginPage.vue')
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/HomePage.vue')
  },
  {
    path: '/test-card-drawing',
    name: 'TestCardDrawing',
    component: () => import('../views/TestCardDrawing.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  
  // 初始化用户状态（同步）
  if (!userStore.isLoggedIn) {
    userStore.initFromStorage();
  }

  // 如果访问登录页且已登录，重定向到首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    next('/');
    return;
  }

  // 如果访问登录页且未登录，直接放行
  if (to.path === '/login') {
    next();
    return;
  }

  // 对于所有其他路由，都需要检查登录状态
  if (!userStore.isLoggedIn) {
    // 未登录，重定向到登录页
    next('/login');
    return;
  }

  next();
});

export default router;
